package com.share.user.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.context.SecurityContextHolder;
import com.share.common.core.exception.ServiceException;
import com.share.user.api.domain.UserInfo;
import com.share.user.api.domain.UserLoginLog;
import com.share.user.api.modei.UpdateUserLogin;
import com.share.user.mapper.UserInfoMapper;
import com.share.user.mapper.UserLoginLogMapper;
import com.share.user.service.IUserInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 用户Service业务层处理
 *
 * @author atguigu
 * @date 2025-07-18
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    private static final String DEFAULT_AVATAR_URL = "https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg";

    private final UserLoginLogMapper userLoginLogMapper;

    private final WxMaService wxMaService;

    /**
     * 查询用户列表
     *
     * @param userInfo 用户
     * @return 用户
     */
    @Override
    public List<UserInfo> selectUserInfoList(UserInfo userInfo) {
        return this.baseMapper.selectUserInfoList(userInfo);
    }

    /**
     * 小程序授权登录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfo wxLogin(String code) {
        if (StringUtils.isBlank(code)) {
            throw new ServiceException("微信登录code不能为空");
        }
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openId = sessionInfo.getOpenid();
            log.info("【小程序授权】获取openId成功，openId={}", openId);

            UserInfo userInfo = this.baseMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openId));

            if (userInfo == null) {
                userInfo = createNewUser(openId);
                this.baseMapper.insert(userInfo);
                log.info("【小程序授权】创建新用户成功，userId={}", userInfo.getId());
            }
            return userInfo;
        } catch (WxErrorException e) {
            log.error("【小程序授权】获取openId失败，code={}", code, e);
            throw new ServiceException("微信登录失败：" + e.getError().getErrorMsg());
        } catch (Exception e) {
            log.error("【小程序授权】登录过程发生未知异常，code={}", code, e);
            throw new ServiceException("微信登录异常，请稍后再试");
        }
    }

    private UserInfo createNewUser(String openId) {
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname("用户_" + System.currentTimeMillis());
        userInfo.setAvatarUrl(DEFAULT_AVATAR_URL);
        userInfo.setWxOpenId(openId);
        userInfo.setCreateTime(new Date());
        return userInfo;
    }


    /**
     * 更新用户登录信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserLogin(UpdateUserLogin updateUserLogin) {
        if (updateUserLogin == null || updateUserLogin.getUserId() == null) {
            log.error("【用户登录】更新登录信息失败，参数为空");
            throw new IllegalArgumentException("更新用户登录信息参数不能为空");
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setId(updateUserLogin.getUserId());
        userInfo.setLastLoginIp(updateUserLogin.getLastLoginIp());
        userInfo.setLastLoginTime(updateUserLogin.getLastLoginTime());
        userInfo.setUpdateTime(new Date());

        int updateCount = this.baseMapper.updateById(userInfo);
        if (updateCount == 0) {
            log.warn("【用户登录】更新登录信息失败，用户不存在，userId={}", updateUserLogin.getUserId());
            return false;
        }

        recordLoginLog(updateUserLogin);
        log.info("【用户登录】更新登录信息成功，userId={}, ip={}", updateUserLogin.getUserId(), updateUserLogin.getLastLoginIp());
        return true;
    }

    /**
     * 是否免押金
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean isFreeDeposit() {
        UserInfo userInfo = this.getById(SecurityContextHolder.getUserId());
        userInfo.setDepositStatus("1");
        this.updateById(userInfo);

        return true;
    }

    private void recordLoginLog(UpdateUserLogin updateUserLogin) {
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserId(updateUserLogin.getUserId());
        userLoginLog.setMsg("小程序登录");
        userLoginLog.setIpaddr(updateUserLogin.getLastLoginIp());
        userLoginLog.setCreateTime(new Date());
        userLoginLogMapper.insert(userLoginLog);
    }
}
